'use strict'

const path = require('path')
const { readdirSync } = require('fs')
const { DataTypes } = require('sequelize')
const { sequelize } = require('../../config')
const Router = require('koa-router')
const plugins = require('../../config/plugin')

// 读取文件夹文件并执行
const readFileByFolder = (dir, cb) => {
    // 文件夹路径
    const folderDir = path.resolve(__dirname, dir)

    try {
        // 读取文件夹所有文件
        const files = readdirSync(folderDir)
        files.forEach(file => {
            const filename = file.replace(/.js/, '')
            const content = require(`${folderDir}/${file}`)
            cb && cb(filename, content)
        })
    } catch (error) {
        console.log('------log------', error)
    }
}

// 初始化配置
const initConfig = options => {
    let configs = {}
    readFileByFolder('../../config', (filename, config) => {
        configs = { ...configs, ...config }
    })
    return configs
}

// 初始化controller
const initConctroller = options => {
    const controllers = {}
    readFileByFolder('../controller', (filename, controller) => {
        controllers[filename] = controller(options)
    })
    return controllers
}

// 初始化service
const initService = options => {
    const services = {}
    readFileByFolder('../service', (filename, service) => {
        services[filename] = service(options)
    })
    return services
}

// 初始化扩展
const initExtend = options => {
    const { ctx } = options
    readFileByFolder('../extend', (filename, extend) => {
        ctx[filename] = extend(options)
    })
}

// 初始化表数据字段
const initModel = options => {
    const models = {}
    readFileByFolder('../model', (filename, model) => {
        models[filename] = model({ sequelize, DataTypes })
    })
    return models
}

// 初始化中间件
const initMiddleware = options => {
    const { config, app } = options
    const middlewares = {}
    readFileByFolder('../middleware', (filename, middleware) => {
        middlewares[filename] = middleware(options)
    })
    // 开启中间件
    if (config.middleware && Array.isArray(config.middleware)) {
        config.middleware.forEach(mid => {
            middlewares[mid] && app.use(middlewares[mid])
        })
    }
    return middlewares
}

// 初始化插件
const initPlugin = options => {
  const { ctx } = options
  Object.keys(plugins).forEach(name => {
    const { enable, module } = plugins[name]
    if (enable) {
      const fn = require(module)
      ctx[name] = fn(options)
    }
  })
}

// 初始化路由
const initRouter = options => {
    const router = new Router()
    require('../router')({ router, ...options })
    return router
}

module.exports = {
    initConfig,
    initConctroller,
    initService,
    initExtend,
    initModel,
    initMiddleware,
    initPlugin,
    initRouter
}